package com.teichmann.core.targets.online;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.OnlinePage;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;
import com.teichmann.core.util.CrawlerUtils;

@Url(value = "http://www.sulrevendas.com.br/busca_veiculo.asp")
public class AutoCentro implements OnlinePage {

	private int countCars;
	ArrayList<Car> cars = new ArrayList<Car>();
	NodeVisitor visitor = new NodeVisitor() {

		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("td".equalsIgnoreCase(name)
					&& (tag.getAttribute("onmouseover") != null && (tag
							.getAttribute("onmouseover")
							.contains("this.style.backgroundColor = '#E0E0E0';")))) {

				cars.add(extractInformation(tag));
				countCars++;

			}
		}
	};

	public ArrayList<Car> performSearch(String parameter) throws IOException {

		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("modeloext", parameter);

		String responseBody = ConnectionUtils.get(this.getClass().getAnnotation(Url.class)
				.value()+"?modeloext=" + parameter);

		int numberOfPages = org.apache.commons.lang.StringUtils.countMatches(responseBody,
				"pq=&pag=");
		
		String sid = StringUtils.substringBetween(responseBody,"?sid=", "\"");

		numberOfPages = (numberOfPages % 2 == 0) ? (numberOfPages / 2) + 1
				: numberOfPages++;

		for (int x = 1; x <= numberOfPages; x++) {
			responseBody = ConnectionUtils
					.get("http://www.autocentro.com.br/execs/mostrapesquisa.cgi?sid=" + sid
							+ "&start=" + (x>1? x*12+1: 1));

			Parser parser = new Parser(new Lexer(responseBody));
			try {
				parser.visitAllNodesWith(visitor);
			} catch (ParserException e) {
				e.printStackTrace();
			}
		}

		return cars;

	}

	public Car extractInformation(Tag line) {
		Car car = new Car();
		int count = 1;
		try {

			NodeList details = line.getChildren();
			details = details.extractAllNodesThatMatch(new NodeFilter() {
				public boolean accept(Node arg0) {
					if (arg0 instanceof TableTag) {
						return true;

					}

					return false;
				}

			});

			Pattern intOnly = Pattern.compile("\\d+");

			details = details.elementAt(0).getChildren();

			car.setMontadora(details.elementAt(1).getChildren().elementAt(3).getChildren()
					.elementAt(1).getText());
			car.setModelo(details.elementAt(1).getChildren().elementAt(3).getChildren()
					.elementAt(4).getText());
			// car.setPlaca(CrawlerUtils.removeUnusedFields(details.elementAt(1).getChildren().elementAt(1).getChildren().elementAt(0).getText()));

			// ano fabricacao
			String anoModelo = CrawlerUtils.removeUnusedFields(details.elementAt(1)
					.getChildren().elementAt(5).getChildren().elementAt(2).getText()
					.split("/")[1]);
			String anoFabricacao = CrawlerUtils.removeUnusedFields(details.elementAt(1)
					.getChildren().elementAt(5).getChildren().elementAt(2).getText()
					.split("/")[0]);
			Matcher matcher = intOnly.matcher(anoModelo);
			if (matcher.find()) {
				car.setAnoModelo(new Integer(matcher.group()));
			} else {
				car.setAnoModelo(new Integer(anoModelo));
			}

			matcher = intOnly.matcher(anoFabricacao);
			if (matcher.find()) {
				car.setAnoFabricacao(new Integer(matcher.group()));
			} else {
				car.setAnoFabricacao(new Integer(anoFabricacao));
			}

			car.setCor(CrawlerUtils.removeUnusedFields(details.elementAt(1).getChildren()
					.elementAt(7).getChildren().elementAt(2).getText()));
			car.setCombustivel(CrawlerUtils.removeUnusedFields(details.elementAt(1)
					.getChildren().elementAt(9).getChildren().elementAt(2).getText()));

			if (details.elementAt(3).getChildren().elementAt(5).getChildren() != null && StringUtils.isNotEmpty(details.elementAt(3).getChildren().elementAt(5)
					.getChildren().elementAt(0).getText())) {
				matcher = intOnly.matcher(details.elementAt(3).getChildren().elementAt(5)
						.getChildren().elementAt(0).getText());
				if (matcher.find()) {
					car.setKm(new Integer(matcher.group()));
				}
			}

			String url =details.elementAt(3).getChildren().elementAt(1).getChildren().elementAt(0).getText();
			matcher = intOnly.matcher(url);
			if (matcher.find()) {
				int codUrl = (new Integer(matcher.group()));
				car.setUrl("http://www.sulrevendas.com.br/detalhes.asp?id=" + codUrl);
			}
			car.setValor(CrawlerUtils.removeUnusedFields(details.elementAt(3).getChildren()
					.elementAt(7).getChildren().elementAt(1).getText()));
			car.setRevenda(new Seller(this.getClass().getSimpleName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;

	}

}
